#include "clientsocket.h"
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>

ClientSocket::ClientSocket(QObject *parent)
    : QTcpSocket{parent}
{
    connect(this,&ClientSocket::connected,this,[=](){
        is_connected = true;
    });
    connect(this,&ClientSocket::disconnected,this,[=](){
        qDebug()<<"断开";
        is_connected = false;
    });
    connect(this,&ClientSocket::readyRead,this,&ClientSocket::recv);
}

void ClientSocket::connectToServer()
{
    connectToHost(server_ip,server_port);
}

bool ClientSocket::readConfFile(const QString &path)
{
    QFile file(path);
    if(!file.open(QIODevice::ReadOnly)){
        return false;
    }
    QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
    QJsonObject obj = doc.object();
    server_ip = obj["server_ip"].toString();
    server_port = obj["server_port"].toInt();
    return true;
}

void ClientSocket::move(MoveDirection dir, int speed)
{
    QJsonDocument doc;
    QJsonObject obj;
    obj["status"] = dir_map[dir];
    obj["speed"] = speed;
    doc.setObject(obj);
    write(doc.toJson());
}

void ClientSocket::servosMove(Servos servos, int angle)
{
    QJsonDocument doc;
    QJsonObject obj;
    obj["status"] = servos_map[servos];
    obj["angle"] = angle;
    doc.setObject(obj);
    write(doc.toJson());
}

void ClientSocket::stop()
{
    QJsonDocument doc;
    QJsonObject obj;
    obj["status"] = "stop";
    doc.setObject(obj);
    write(doc.toJson());
}

void ClientSocket::recv() {}
